package com.hlyj.http.base.tool.lib_hlyj_base.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class VpnDetector {

    /**
     * 综合检测是否开启代理，0 表示未开启，1 表示开启
     */
    public static String isProxyActive(Context context) {
        return isVpnActive(context) ? "1" : "0";
    }

    /**
     * 综合检测VPN是否激活（推荐使用此方法）
     */
    public static boolean isVpnActive(Context context) {
        return checkByConnectivityManager(context) || checkByNetworkCapabilities(context)
                || checkByNetworkInterfaces();
    }

    /**
     * 方法1：通过ConnectivityManager检测（兼容旧版Android）
     */
    private static boolean checkByConnectivityManager(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null) return false;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Network[] networks = cm.getAllNetworks();
                for (Network network : networks) {
                    NetworkInfo networkInfo = cm.getNetworkInfo(network);
                    if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_VPN
                            && networkInfo.isConnected()) {
                        return true;
                    }
                }
            } else {
                // 旧版Android的检测方式
                NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_VPN);
                return networkInfo != null && networkInfo.isConnected();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 方法2：通过NetworkCapabilities检测（Android 6.0+）
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private static boolean checkByNetworkCapabilities(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null) return false;

            Network activeNetwork = cm.getActiveNetwork();
            if (activeNetwork == null) return false;

            NetworkCapabilities caps = cm.getNetworkCapabilities(activeNetwork);
            return caps != null && caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 方法3：通过检查网络接口检测VPN
     */
    private static boolean checkByNetworkInterfaces() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                // VPN接口通常以"tun"、"tap"、"ppp"或"pptp"开头
                if (iface.isUp() && (iface.getName().startsWith("tun")
                        || iface.getName().startsWith("ppp")
                        || iface.getName().startsWith("pptp"))) {
                    return true;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return false;
    }
}